package dao

import (
	"diancan/logUtlis"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"github.com/spf13/viper"
	"log"
	"os"
)

var DB *gorm.DB
var err error

var ViperConfig *viper.Viper


/*
初始化配置文件
*/
func NewViper()  {
	//获取项目执行路径
	path, err := os.Getwd()
	if err != nil {
		logUtlis.MainLog.Error("项目执行路径出错："+err.Error())
		return
	}
	ViperConfig = viper.New()
	//这只要读取的文件名
	ViperConfig.SetConfigName("config")
	//设置要读取的文件类型
	ViperConfig.SetConfigType("yml")
	//设置要读取的文件路径
	ViperConfig.AddConfigPath(path+"/config")

	//尝试进行配置读取
	if err := ViperConfig.ReadInConfig(); err != nil {
		logUtlis.MainLog.Error("尝试读取文件配置失败:"+err.Error())
		return
	}

}
/*
初始化mysql
*/
func InitMysql() {
	root := ViperConfig.GetString("mysql.username")
	password := ViperConfig.GetString("mysql.password")
	path := ViperConfig.GetString("mysql.path")
	port := ViperConfig.GetString("mysql.port")
	dbName := ViperConfig.GetString("mysql.db-name")
	config := ViperConfig.GetString("mysql.config")
/*	max_idle_conns := RedisConfig.GetInt("mysql.max-idle-conns")
	max_open_conns := RedisConfig.GetInt("mysql.max-open-conns")*/
	logMode := ViperConfig.GetBool("mysql.log-mode")

	// root:123456@/diancan?charset=utf8mb4&parset=True&loc=Local

	sprintf := fmt.Sprintf("%s:%s@tcp(%s%s)/%s?%s", root, password, path,port, dbName, config)
	DB, err = gorm.Open("mysql", sprintf)
	if err != nil {
		logUtlis.MainLog.Error("数据库连接失败:"+err.Error())
		log.Fatalln("数据库连接失败",err.Error())
	}
	//defer DB.Close()
	DB.LogMode(logMode)
	fmt.Println("数据库连接成功！")


}
